package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/7/13 18:12
 * @email kekecany@163.com
 */

class Meal {
    private int orderNum;

    Meal(int orderNum) {
        this.orderNum = orderNum;
    }

    @Override
    public String toString() {
        return "Meal{" +
                "orderNum=" + orderNum +
                '}';
    }
}

class WaitPerson implements Runnable {
    private Restaurant restaurant;

    WaitPerson(Restaurant restaurant) {
        this.restaurant = restaurant;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal == null) {
                        wait();
                    }
                }
                System.out.println("wait person got " + restaurant.meal);

                synchronized (restaurant.chef) {
                    restaurant.meal = null;
//                    notifyAll();
                    restaurant.chef.notifyAll();
                }
            }
        } catch (InterruptedException e) {
            System.out.println("wait person exit by interruption");
        }
    }
}

class Chef implements Runnable {

    private Restaurant restaurant;

    private int count = 0;

    Chef(Restaurant restaurant) {
        this.restaurant = restaurant;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal != null) {
                        wait();
                    }
                }
                if (++count > 10) {
                    restaurant.executorService.shutdownNow();
                    System.out.println("finished supply...");
                }

                synchronized (restaurant.waitPerson) {
                    restaurant.meal = new Meal(count);
//                    notifyAll();
                    restaurant.waitPerson.notifyAll();
                }
                TimeUnit.MILLISECONDS.sleep(100);
            }
        } catch (InterruptedException e) {
            System.out.println("chef exit by interruption");
        }


    }
}

public class Restaurant {
    Meal meal;
    final WaitPerson waitPerson = new WaitPerson(this);
    final Chef chef = new Chef(this);
    ExecutorService executorService = Executors.newCachedThreadPool();

    private Restaurant() {
        executorService.execute(waitPerson);
        executorService.execute(chef);
    }

    public static void main(String[] args) {
        new Restaurant();
    }
}
